﻿// Imports
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Nickel
{

    /// <summary>
    /// Renders template
    /// </summary>
    public class _Default : Page
    {

        /// <summary>
        /// Article list
        /// </summary>
        private List<Article> articles = null;

        /// <summary>
        /// Selected article
        /// </summary>
        private Article article = null;

        /// <summary>
        /// Author to activate
        /// </summary>
        private Author authorToActivate;

        /// <summary>
        /// Page end
        /// </summary>
        private int intEnd;

        /// <summary>
        /// Page number
        /// </summary>
        private int intPage;

        /// <summary>
        /// Page start
        /// </summary>
        private int intStart;

        /// <summary>
        /// Output string
        /// </summary>
        private string strOutput;

        /// <summary>
        /// Signed in author
        /// </summary>
        private Author user;

        /// <summary>
        /// Handles page initialization
        /// </summary>
        /// <param name="sender">Sender object</param>
        /// <param name="e">Event arguments</param>
        protected override void Page_Init(object sender, EventArgs e)
        {

            // Call init on base class
            base.Page_Init(sender, e);

            // Initialize inherited strings
            strError = string.Empty;
            strMetaDescription = Settings.SITE_DESCRIPTION;
            strMetaKeywords = Settings.SITE_KEYWORDS;
            strPageTitle = string.Empty;

            // Read argument
            strArgument = HttpContext.Current.Items[Constants.INPUT_ARGUMENT] == null ? string.Empty : HttpContext.Current.Items[Constants.INPUT_ARGUMENT] as string;

            // Set page number
            intPage = 1;
            int.TryParse(strArgument, out intPage);

            // Second argument specified
            if (HttpContext.Current.Items[Constants.INPUT_PAGE] != null) 
                int.TryParse(HttpContext.Current.Items[Constants.INPUT_PAGE] as string, out intPage);

            // Set page title
            string strTitle = Settings.SITE_TITLE + " . " + Settings.SITE_TAG_LINE;

            // Decalre string to fill buffer div for search engine/site map compatibility
            string strBuffer = string.Empty;

            // Argument specified
            if (strArgument != string.Empty)
            {

                // Use argument to find article list
                articles = Data.GetArticlesByTag(strArgument);
                if (articles == null) 
                    articles = Data.GetArticlesByAuthorName(strArgument);
                if (articles == null) 
                    articles = Data.GetArticlesByAuthorId(strArgument);
                if (articles == null)
                {

                    // Use argument to find single article
                    article = Data.GetArticleByTitle(strArgument);
                    if (article == null) 
                        article = Data.GetArticleById(strArgument);

                    // Set article to null if it is unpublished and trying to be viewed by a non-admin
                    if (article != null && !article.Published && (user == null || !user.Admin)) 
                        article = null;

                    // No article
                    if (article == null)
                    {

                        // Set articles
                        articles = Data.Articles;

                    }
                    else
                    {

                        // Get meta data
                        strMetaDescription = article.Description;
                        strMetaKeywords = article.Keywords.Join(", ");

                        // Write buffer
                        strBuffer = Markup.FindImage(article.Text) + StringHelper.RemoveHtml(Markup.Parse(article.Text));
                        if (article.CommentsEnabled) 
                            foreach (Comment comment in article.Comments) 
                                strBuffer += "<br /><br />" + StringHelper.RemoveHtml(Markup.ParseLite(comment.Text));

                    }

                }

            }
            else
            {

                // Set articles
                articles = Data.Articles;

            }

            // Articles found
            if (articles != null)
            {

                // Use all articles if not a list
                if (articles == null)
                    articles = Data.Articles;

                // Write links into buffer
                foreach (Article articleLink in articles)
                    if (articleLink.Published) 
                        strBuffer += "<a href=\"" + strBaseUrl + StringHelper.Encode(articleLink.Title) + "\">" + articleLink.Title + "</a><br />";

            }

            // Clean up
            article = null;
            articles = null;

            // We have authors and want to show 'em
            string strAuthors = string.Empty;
            if (Data.Authors.Count > 0 && Settings.LINK_AUTHORS)
            {

                // Initialize authors with title
                strAuthors = "<p class=\"tagTitle\">" + Labels.PANEL_AUTHORS + "</p>";

                // Iterate through authors
                int authorsAdded = 0;
                foreach (Author author in Data.Authors)
                {

                    // Only list admins
                    if (author.Admin)
                    {

                        // Increase added author count
                        authorsAdded++;

                        // Encode author name
                        string authorUrl = StringHelper.Encode(author.Name);

                        // Write link
                        strAuthors += "<a href=\"" + strBaseUrl + authorUrl + "\" class=\"tagLink" + (authorUrl == StringHelper.Encode(strArgument) ? "Active" : "") + "\">" + StringHelper.ToTitleCase(author.Name) + "</a><br />\n";

                    }

                }

                // Clear string if no authors
                if (authorsAdded < 1) 
                    strAuthors = string.Empty;

            }

            // We have tags
            string strTags = string.Empty;
            if (Data.Tags.Count > 0)
            {

                // Initialize tags with home link
                strTags = "<p class=\"tagTitle\">" + Labels.PANEL_TAGS + "</p>" +
                    "<a href=\"" + strBaseUrl + "\" class=\"tagLink" +
                    (strArgument == string.Empty ? "Active" : "") + "\">All</a><br />\n";

                // Iterate through tags
                foreach (string tag in Data.Tags)
                {

                    // Encode tag
                    string tagUrl = StringHelper.Encode(tag);

                    // Write link
                    strTags += "<a href=\"" + strBaseUrl + tagUrl + "\" class=\"tagLink" + (tagUrl == StringHelper.Encode(strArgument) ? "Active" : "") + "\">" + StringHelper.ToTitleCase(tag) + "</a><br />\n";

                }

            }

            // Set about panel HTML
            string strAbout = "<div class=\"tags\"><p class=\"tagTitle\">" + Labels.PANEL_ABOUT +
                "</p><p>" + Settings.ABOUT + "</p></div>";

            // Set account title
            string strAccountTitle = "<p class=\"tagTitle\">" + Labels.PANEL_ACCOUNT + "</p>";

            // Load template
            StreamReader reader = new StreamReader(Server.MapPath(@"~/template.html"));
            string strOutput = reader.ReadToEnd();

            // Close template
            reader.Close();
            reader = null;

            // Replace strings in template
            strOutput = strOutput.Replace("src=\"/", "src=\"" + strBaseUrl);
            strOutput = strOutput.Replace("href=\"/", "href=\"" + strBaseUrl);
            strOutput = strOutput.Replace("###about###", strAbout);
            strOutput = strOutput.Replace("###buffer###", strBuffer);
            strOutput = strOutput.Replace("###argument###", strArgument);
            strOutput = strOutput.Replace("###authors###", strAuthors);
            strOutput = strOutput.Replace("###accountTitle###", strAccountTitle);
            strOutput = strOutput.Replace("###baseUrl###", strBaseUrl);
            strOutput = strOutput.Replace("###description###", StringHelper.ToAttribute(strMetaDescription));
            strOutput = strOutput.Replace("###header###", Settings.HEADER.Replace("###url###", strBaseUrl).Replace("###title###", Settings.SITE_NAME));
            strOutput = strOutput.Replace("###keywords###", StringHelper.ToAttribute(strMetaKeywords));
            strOutput = strOutput.Replace("###page###", intPage.ToString());
            strOutput = strOutput.Replace("###tags###", strTags);
            strOutput = strOutput.Replace("###title###", strTitle);

            // Write HTML
            Response.Write(strOutput);

        }

    }

}
